cap program drop ipw
program define ipw, rclass
syntax varlist(max=2) [if], pscore(string) estimator(string)
qui{
   //Data
   tokenize `varlist'
   local Y = "`1'"
   local T = "`2'"
   local p = "`pscore'";
   //control of option if
   if "`if'"!="" local andif = "& `if'"
   sum `T' `if'
   local pi = r(mean)
   tempname yw 
  //IPW1
   if "`estimator'"=="IPW1"{
     gen _weight = `p'/(1-`p')*(1-`pi')/`pi' if `T'==0 `andif'
     replace _weight =  1 if `T'==1 `andif'
     gen `yw' = `Y'*_weight
     sum `yw' if `T'==1
     local mu1 = r(mean)
     sum `yw' if `T'==0
     local mu0 = r(mean)
     return scalar ipw1 = `mu1'-`mu0'
     drop `yw' _weight
	 }
   //IPW2
   if "`estimator'"=="IPW2"{
     gen _weight = (`p'/(1-`p')) if `T'==0 `andif'
	 replace _weight = 1 if `T'==1 `andif'
     reg `Y' `T' [aw=_weight]
     return scalar ipw2 = _b[`T']
	 drop _weight
   }
}
end

*ipw Y T, pscore(phat) estimator(IPW2)
